define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock){

    var sysPath =  getServer() + "/static/app/fxpg/fxMiddleResult";

    var fxMiddleResultFormHtml = sysPath + "/views/fxMiddleResultForm.html";
	var getFxMiddleResultController = function(){
		return getServer() + "/fxMiddleResults";
	};
	var getFxVulnerabilityProvinceController = function () {
		return getServer() + "/fx/fxVulnerabilityProvinces";
	};
	var getFxBuildingsController = function(){
		return getServer() + "/fxBuildingss";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		//initcreateProvince();
		initProvinceSelect("北京市", "北京市", "海淀区");
		initEarthquakeIntensitySelect();
		initDamageDegreeSelect();
		//formValidator2();
		//createFxMiddleResultGrid();
	};
    var initProvinceSelect = function (Province, City, Area) {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() +"/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#citySelect').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#areaSelect").append(htmlArea);
                                    $('#areaSelect').val(Area);
                                    // 列表
                                    createFxMiddleResultGrid();
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#areaSelect").append(htmlArea);
                                                    $('#areaSelect').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#citySelect").append(htmlCity);
                                    $('#citySelect').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
                $('#provinceSelect').val(Province);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };
	var initEarthquakeIntensitySelect = function () {
		$.ajax({
			url: getFxVulnerabilityProvinceController() + "/getValidDictItemsByDictCode/" + "earthquakeIntensity",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("earthquakeIntensitySelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initDamageDegreeSelect = function () {
		$.ajax({
			url: getFxVulnerabilityProvinceController() + "/getValidDictItemsByDictCode/" + "damageDegree",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("damageDegreeSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initEarthquakeIntensitySelectFrom = function () {
		$.ajax({
			url: getFxVulnerabilityProvinceController() + "/getValidDictItemsByDictCode/" + "earthquakeIntensity",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("earthquakeIntensity");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initDamageDegreeSelectFrom = function () {
		$.ajax({
			url: getFxVulnerabilityProvinceController() + "/getValidDictItemsByDictCode/" + "damageDegree",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("damageDegree");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};

	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
		$("#btnSearch").click(function () {
			//if($("#searchForm").valid()){
				computeBuildingsResistEarthquakeAbilityMain();
			//}
		});
        $("#btnReset").click(function () {
        	var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
			initProvinceSelect("北京市", "北京市", "海淀区");
//			$("#provinceSelect").val("北京市");
//          $("#citySelect").val("北京市");
//          $("#areaSelect").val("海淀区");
         	$("#earthquakeIntensitySelect").val("");
         	$("#damageDegreeSelect").val("");
		});
	};
	var computeBuildingsResistEarthquakeAbilityMain = function () {
		var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
		var intensity = $("#earthquakeIntensitySelect").val() || "", damageDegree = $("#damageDegreeSelect").val() || "";
		(intensity == "") ? (intensity = ["6", "7", "8", "9", "10"]) : (intensity = [intensity]);
		(damageDegree == "") ? (damageDegree = ["0", "1", "2", "3", "4"]) : (damageDegree = [damageDegree]);
		for (let k = 0; k < intensity.length; k++) {
			for (let n = 0; n < damageDegree.length; n++) {
				computeBuildingsResistEarthquakeAbility(province, city, area, intensity[k], damageDegree[n], k == intensity.length - 1, n == damageDegree.length - 1);
			}
		}
	};
	var computeBuildingsResistEarthquakeAbility = function (province, city, area, intensity, damageDegree, flag1, flag2) {
		$.ajax({
			url: getFxBuildingsController() + "/getFxBuildingss?province=" + province + "&city=" + city + "&area=" + area,
			type: "get",
			success: function (data) {
				console.log(data);
				if (data && data.length > 0) {
					var weighted_e = 0, acreage = 0, evaluate_res = 0, area2e = {}, area2acreage = {}, vulnerability = 0;
					var buildingIsFinished = {};
					for (let i = 0; i < data.length; i++) {
						buildingIsFinished[data[i].id] = false;
						$.ajax({
							url: getFxVulnerabilityProvinceController() + "/findFxVulnerabilityProvinces?province=" + data[i].province + "&city=" + data[i].city + "&area=" + data[i].area + "&structureType=" + data[i].structureType + "&damageDegree=" + damageDegree,
							type: "get",
							success: function (result) {
								console.log("result: ", result);
								buildingIsFinished[data[i].id] = true;
								if (result && result.length == 1) {
									//console.log("====", data[i].area);
									vulnerability = getIntensityValue(intensity, result[0]);
									//console.log("====", data[i].buildingName, vulnerability);
									weighted_e = data[i].buildingArea * vulnerability;
									acreage = data[i].buildingArea;
									!area2e[data[i].area] ? (area2e[data[i].area] = weighted_e) : (area2e[data[i].area] += weighted_e);
									!area2acreage[data[i].area] ? (area2acreage[data[i].area] = acreage) : (area2acreage[data[i].area] += acreage);
								}
								//console.log(i, data.length);

								if (taskIsFinish(buildingIsFinished)) {
									console.log("############");
									for (var key in area2e) {
										evaluate_res = (area2e[key] / area2acreage[key]).toFixed(2);
										console.log("evaluate_res: ", evaluate_res);
										result[0].calculatedValue = evaluate_res;
										console.log("-------------", key)
										updateComputedValue(result[0], evaluate_res, intensity, damageDegree, flag1, flag2);
									}
								}
							}
						});
					}
				} else {
					$('#fxMiddleResultGrid').datagrid('loadData', {total: 0, rows: []});
					$('#fxMiddleResultGrid').datagrid('appendRow',{});
					var body = $("#fxMiddleResultGrid").data().datagrid.dc.body2;
					var trs = body.find('table tbody').find("tr");
					while (trs.eq(0).find("td").length > 1) {
						if (trs.eq(0).find("td").length == 1) break;
						trs.eq(0).find("td").eq(1).remove();
					}
					trs.eq(0).find("td").eq(0).attr("colspan", 6).attr("width", body.width()).css("text-align", "center").html("查询无数据");
				}
			}
		});
	};
	var getIntensityValue = function (intensityType, data) {
		console.log(intensityType, data);
		if (intensityType == "6") {
			return data.vulnerabilityVI;
		} else if (intensityType == "7") {
			return data.vulnerabilityVII;
		} else if (intensityType == "8") {
			return data.vulnerabilityVIII;
		} else if (intensityType == "9") {
			return data.vulnerabilityIX;
		} else if (intensityType == "10") {
			return data.vulnerabilityX;
		}
	};
	var updateComputedValue = function (data, calculatedValue, intensity, damageDegree, flag1, flag2) {
		var paramter = {
			province: data.province,
			city: data.city,
			area: data.area,
			earthquakeIntensity: intensity,
			damageDegree: damageDegree
		}
		console.log("paramter: ", paramter);
		$.ajax({
			url: getFxMiddleResultController() + "/queryFxMiddleResults?page=1&&rows=10&province=" + data.province + "&city=" + data.city + "&area=" + data.area + "&earthquakeIntensity=" + intensity + "&damageDegree=" + damageDegree,
			contentType:"application/json",
			type: "GET",
			success: function (_data) {
				console.log(_data);
				if (_data && _data.total == 1) {
					var result = _data.rows[0];
					result.calculatedValue = calculatedValue;
					$.ajax({
						url: getFxMiddleResultController(),
						contentType:"application/json",
						data: JSON.stringify(result),
						type: "put",
						success: function (__data) {
							flag1 && flag2 && (Util.alert(__data.message));
							//slidebar.close();
							createFxMiddleResultGrid();
						}
					});
				}
			}
		});
	};

	var createFxMiddleResultGrid= function() {
        $("#fxMiddleResultGrid").datagrid({
            url: getFxMiddleResultController() + "/getFxMiddleResults",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            columns:[[
				{
					field:'province',
					title:'省',
					width:'20%',
					align:'center',
				},
				{
					field:'city',
					title:'市',
					width:'20%',
					align:'center',
				},
				{
					field:'area',
					title:'区（县）',
					width:'20%',
					align:'center'
				},
				{
					field:'earthquakeIntensity',
					title:'地震动强度',
					width:'15%',
					align:'center',
					formatter: function (value) {
						console.log(arguments[1]);
						if (value == "6") {
							return 'VI';
						} else if (value == "7") {
							return 'VII';
						} else if (value == "8") {
							return 'VIII';
						} else if (value == "9") {
							return 'IX';
						} else if (value == "10") {
							return 'X';
						}
					}
				},
				{
					field:'damageDegree',
					title:'破坏程度',
					width:'15%',
					align:'center',
					formatter: function (value) {
						console.log(arguments[1]);
						if (value == "0") {
							return '基本完好';
						} else if (value == "1") {
							return '轻微破坏';
						} else if (value == "2") {
							return '中等破坏';
						} else if (value == "3") {
							return '严重破坏';
						} else if (value == "4") {
							return '完全破坏';
						}
					}
				},
				{
					field:'calculatedValue',
					title:'计算值',
					width:'10%',
					align:'center',
					//editor:{type:'numberbox'},
				}
            ]],
            toolbar: [/*{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addFxMiddleResult();
                }
            }, {
				iconCls: 'fa fa-plus-circle',
				text:"导出模板",
				handler: function(){
					exportMiddleResultTemplet();
				}
			}, {
				iconCls: 'fa fa-plus-circle',
				text:"导入",
				handler: function(){
					//addFxMiddleResult();
					alert("功能暂未实现");
				}
			},*/ {
				iconCls: 'fa fa-plus-circle',
				text:"导出",
				handler: function(){
					exportMiddleResult();
				}
			}, /*{
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteFxMiddleResult();
                }
            }*/],
            /*onClickCell: function (index, field, value) {
                if (endEditing()) {
                    $('#fxMiddleResultGrid').datagrid('selectRow', index).datagrid('editCell', {
                        index: index,
                        field: field
                    });
                    editIndex = index;
                    mergeCells("fxMiddleResultGrid", "province,city,area,earthquakeIntensity");
                }
            },*/
//          onDblClickCell: function (index, field, value) {
//				$("#fxMiddleResultGrid").datagrid('endEdit', index);
//				debugger;
//				mergeCells("fxMiddleResultGrid", "province,city,area,structureType");
//        	},
            /*onAfterEdit: function (index, row, changes) {
//             $("#fxMiddleResultGrid").datagrid('endEdit', index);
//			    $.ajax({
//			        url : '要改变后台数据的controller路径?fieId1='+row.属性1,
//			        data:{fieId2:row.fieId}, //额外的参数
//			        dataType: "text",//响应结果为文本
//			        success:function (data) {
//			            $.messager.alert('消息', data);
//			        }
//			    });
				//console.log(index, row, changes);
	            $.ajax({
	                url: getFxMiddleResultController(),
	                contentType: "application/json",
	                data: JSON.stringify(row),
	                type: "put",
	                success: function (data) {
	                    Util.alert(data.message);
	                    createFxMiddleResultGrid();
	                }
	            });

            },*/
            queryParams:{
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
//              earthquakeIntensity: $("#earthquakeIntensitySelect").val(),
//              damageDegree: $("#damageDegreeSelect").val(),
            },
            onLoadSuccess: function (data) {
                //垂直合并单元格
                mergeCells("fxMiddleResultGrid", "province,city,area,earthquakeIntensity");
            },
//          pagination: true,
//          pageSize: 10
        });
    };
    $.extend($.fn.datagrid.methods, {
        editCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat(
                    $(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });
    var editIndex = undefined;

    //结束编辑
    function endEditing() {
        if (editIndex == undefined) {
            return true
        }
        if ($('#fxMiddleResultGrid').datagrid('validateRow', editIndex)) {
            $('#fxMiddleResultGrid').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };

    //合并单元格方法
    /**
     * EasyUI DataGrid根据字段动态合并单元格
     * @param colList 要合并table的id, 此例子中是tTable
     * @param colList 要合并的列,多个列用逗号分隔(例如："tempParam,flowCode,queryParam");
     */
    function mergeCells(tableID, colList) {
        var colArray = colList.split(",");
        var tTable = $("#" + tableID);
        var tableRows = tTable.datagrid("getRows");
        var tableRowCnts = tableRows.length;
        var rowspan;
        var preTxt = "";
        var curTxt = "";
        for (j = colArray.length - 1; j >= 0; j--) {
            preTxt = "";
            rowspan = 1;
            for (i = 0; i <= tableRowCnts; i++) {
                if (i == tableRowCnts) {
                    curTxt = "";
                } else {
                    curTxt = tableRows[i][colArray[j]];
                }
                if (preTxt == curTxt) {
                    rowspan += 1;
                } else {
                    tTable.datagrid("mergeCells", {
                        index: i - rowspan,
                        field: colArray[j],//合并字段
                        rowspan: rowspan,
                        colspan: null
                    });
                    rowspan = 1;
                }
                preTxt = curTxt;
            }
        }
    };
	var formValidator = function(){
		$("#fxMiddleResultForm").validate({
			rules : {
				province : {
					required : true,
				},
				city : {
					required : true,
				},
				area : {
					required : true,
				},
				earthquakeIntensity : {
					required : true,
				},
				damageDegree : {
					required : true,
				},
			},
			messages : {
				province : {
					required : "省不允许为空!",
				},
				city : {
					required : "市不允许为空!",
				},
				area : {
					required : "区/县不允许为空!",
				},
				earthquakeIntensity : {
					required : "地震动强度不允许为空!",
				},
				damageDegree : {
					required : "破坏程度不允许为空!",
				},
			}
		});
	};
	var formValidator2 = function(){
		$("#searchForm").validate({
			rules : {
				provinceSelect : {
					required : true,
				},
				citySelect : {
					required : true,
				},
				areaSelect : {
					required : true,
				},
				earthquakeIntensitySelect : {
					required : true,
				},
				damageDegreeSelect : {
					required : true,
				},
			},
			messages : {
				provinceSelect : {
					required : "省不允许为空!",
				},
				citySelect : {
					required : "市不允许为空!",
				},
				areaSelect : {
					required : "区/县不允许为空!",
				},
				earthquakeIntensitySelect : {
					required : "地震动强度不允许为空!",
				},
				damageDegreeSelect : {
					required : "破坏程度不允许为空!",
				},
			}
		});
	};
	var getFxMiddleResult = function(id){
		$.ajax({
			url: getFxMiddleResultController() + "/"+id,
			type: "get",
			success: function (data) {
				editProvince(data.province, data.city, data.area);
				Tool.deserialize("fxMiddleResultForm", data);
			}
		});
	};
	var editProvince = function (Province, City, Area) {
		debugger;
		var html = "";
		$("#city").append(html);
		$("#area").append(html);
		$.ajax({
			url: getServer() +"/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					if (item.divisionName == Province) {
						debugger;
						var divisionId = item.divisionId;
						var htmlCity = '';
						if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
							$("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
							$('#city').val(City);
							var htmlArea = '';
							$.ajax({
								url: getServer()+"/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									$.each(data, function (idx, item) {
										htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#area").append(htmlArea);
									$('#area').val(Area);
								}
							});

						} else {
							$.ajax({
								url: getServer()+"/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									debugger;
									$.each(data, function (idx, item) {
										if (item.divisionName == City) {
											var divisionId = item.divisionId;
											var htmlArea = '';
											$.ajax({
												url: getServer()+"/divisions/" + divisionId + "/subdivisions",
												contentType: "application/json",
												type: "get",
												success: function (data) {
													$.each(data, function (idx, item) {
														htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
													});
													$("#area").append(htmlArea);
													$('#area').val(Area);
												}
											});
										}
										htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#city").append(htmlCity);
									$('#city').val(City);
								}
							});
						}
					}
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#province").append(html);
				$('#province').val(Province);
			}
		});
		$("#province").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#city option").remove();
			$("#city").append(html);
			$("#area option").remove();
			$("#area").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer()+"/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#city").append(html);
				}
			});
		});
		$("#city").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#area option").remove();
			$("#area").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer()+"/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#area").append(html);
				}
			});
		});
	}
	var addFxMiddleResult = function () {
		var slidebar = Util.slidebar({
			url: fxMiddleResultFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {
				initcreateProvince();
				initEarthquakeIntensitySelectFrom();
				initDamageDegreeSelectFrom();
				formValidator();
				$("#saveBtn").on("click", function () {
					if($("#fxMiddleResultForm").valid()){
						var data = Tool.serialize("fxMiddleResultForm");
						$.ajax({
							url: getFxMiddleResultController() ,
                            contentType:"application/json",
							data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
                                createFxMiddleResultGrid();
							}
						});
					}
				});
			}
		});
	};
	window._editFxMiddleResult = function(fxMiddleResultId) {
		var slidebar = Util.slidebar({
			url: fxMiddleResultFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {
				initEarthquakeIntensitySelectFrom();
				initDamageDegreeSelectFrom();
				formValidator();
				getFxMiddleResult(fxMiddleResultId);
				$("#saveBtn").on("click", function () {
					if($("#fxMiddleResultForm").valid()){
						var data = Tool.serialize("fxMiddleResultForm");
						$.ajax({
							url: getFxMiddleResultController(),
                            contentType:"application/json",
                            data: JSON.stringify(data),
							type: "put",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
								createFxMiddleResultGrid();
							}
						});
					}
				});
			}
		});
	};
	var deleteFxMiddleResult = function() {
		var rows = $("#fxMiddleResultGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.id + ",";

			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getFxMiddleResultController() ,
				data: {
					ids : ids
				},
				type: "delete",
				success: function (data) {
					createFxMiddleResultGrid();
				}
			});
		}, function() {
			return;
		});

	};

	var exportMiddleResultTemplet = function () {
		window.location.href = getServer() + "/excel/中间结果数据信息模板.xlsx";
	}
	var exportMiddleResult = function () {
		let province = $("#provinceSelect").val();
		let city = $("#citySelect").val();
		let area = $("#areaSelect").val();
		let eqIntensity = $("#earthquakeIntensitySelect").val();
		let damageDegree = $("#damageDegreeSelect").val();
		window.location.href = getFxMiddleResultController() + "/export?province=" + province + "&city=" + city + "&area=" + area +
					"&earthquakeIntensity= " + eqIntensity + " &damageDegree=" + damageDegree;
	};

	var taskIsFinish = function (obj) {
		for (var _key in obj) if (!obj[_key]) return false;
		return true;
	}

	return {
		init:init
	};
});
